extends ColorRect

# 定义信号
signal animation_completed
@export var spacing := 30
@onready var balls_multimesh: MultiMeshInstance2D = $balls_multimesh


func _ready() -> void:
	show_scene_grid()


# 场景网格可视化（不创建小球，只绘制网格）
func show_scene_grid() -> void:

	# 获取当前视口大小
	var viewport_size = get_viewport_rect().size	
	# 计算需要的网格线数量（确保覆盖整个视口）
	var grid_width = int(ceil(viewport_size.x / spacing)) + 2  # 添加少量余量
	var grid_height = int(ceil(viewport_size.y / spacing)) + 2
	 #创建小球和动画
	setup_multimesh_balls(grid_width, grid_height, spacing)



func setup_multimesh_balls(grid_width: int, grid_height: int, spacing: int) -> void:

	# 获取已在编辑器中设置的MultiMesh
	var multimesh = balls_multimesh.multimesh	
	# 动态设置实例数量
	var total_instances = grid_width * grid_height
	multimesh.instance_count = total_instances		
	# 设置每个实例的变换
	var index = 0
	for i in range(grid_width):
		for j in range(grid_height):
			var transform = Transform2D()
			transform.origin = Vector2(i, j) * spacing	# 设置位置
			transform = transform.scaled(Vector2(0, 0)) # 设置缩放
			multimesh.set_instance_transform_2d(index, transform) 
			index += 1	
	# 创建动画
	animate_multimesh_balls(multimesh, grid_width, grid_height)


func animate_multimesh_balls(multimesh: MultiMesh, grid_width: int, grid_height: int) -> void:
	var index = 0
	# 为每个实例创建动画
	for i in range(grid_width):
		for j in range(grid_height):
			# 创建与create_balls_with_animation相同的动画序列
			var tween = create_tween()
			# 延迟出现
			tween.tween_interval((i+j)*0.03)
			# 淡入动画
			tween.tween_method(func(scale: float):
				var transform = Transform2D()
				transform.x = Vector2(scale, 0)
				transform.y = Vector2(0, scale)
				transform.origin = Vector2(i, j) * spacing
				multimesh.set_instance_transform_2d(index, transform)
			, 0.0, 1.0, 0.5)
			#索引+1	
			index += 1
			
	# 计算最长的动画时间
	var max_delay = (grid_width + grid_height - 2) * 0.03
	var total_animation_time = max_delay + 0.5		
	# 等待动画完成后发送信号
	await get_tree().create_timer(total_animation_time).timeout
	print("动画完成，发送信号")
	emit_signal("animation_completed")
	
	
	







	
	
